package com.ohuang.wallpapermanager.workmanager

import android.content.Context
import androidx.work.Constraints
import androidx.work.ExistingPeriodicWorkPolicy
import androidx.work.NetworkType
import androidx.work.PeriodicWorkRequest
import androidx.work.WorkManager
import com.ohuang.wallpapermanager.config.LocalConfig
import com.ohuang.wallpapermanager.util.AppUtil
import java.util.concurrent.TimeUnit


object CarouseWallPaperWorkManager {
    private val WORK_TAG = "CarouseWallPaperWork"

    fun start(isKeep:Boolean) {
        if (LocalConfig.isWorkManagerEnable) {
            addWork(AppUtil.getInstance().context,isKeep)
        } else {
            cancelWork(AppUtil.getInstance().context)
        }
    }

    private fun addWork(context: Context, isKeep: Boolean = false) {
        realAddWork(context,isKeep)
    }


    private fun realAddWork(context: Context,isKeep:Boolean=false) {
        val constraints: Constraints = Constraints.Builder()
            .setRequiresBatteryNotLow(true)
            .build()
        val request =
            PeriodicWorkRequest.Builder(CarouseWallPaperWork::class.java, 15, TimeUnit.MINUTES)
                .setConstraints(constraints)
                .addTag(WORK_TAG)
                .build()
        WorkManager.getInstance(context)
            .enqueueUniquePeriodicWork(WORK_TAG,if (isKeep) ExistingPeriodicWorkPolicy.KEEP else ExistingPeriodicWorkPolicy.UPDATE, request)
    }

    private fun cancelWork(context: Context) {
        WorkManager.getInstance(context).cancelUniqueWork(WORK_TAG)
    }
}